package com.opgea.crm.web.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.common.vo.ProjectDocumentVo;
import com.opgea.crm.domain.entities.ProjectDetails;
import com.opgea.crm.domain.entities.ProjectDocuments;
import com.opgea.crm.domain.modal.FileUploadBean;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.services.ProjectDetailsService;
import com.opgea.crm.services.QualifierService;
import com.opgea.crm.web.modal.LoggedUser;

@Controller
@RequestMapping(value="projectdocument")
public class ProjectDocumentController {
	
	private static final String FILE_UPLOAD_SUCCESS_RESPONSE = 
		"{\"success\":%s,\"message\":\"%s\",\"fileData\":{\"size\":%s," +
		" \"name\":\"%s\", \"type\":\"%s\"}}";

	Logger logger=Logger.getLogger(ProjectDocumentController.class);
	
	@Autowired
	ProjectDetailsService projectDetailsService;
	@Autowired
	QualifierService qualifierService;
	
	
	protected String buildSuccessFileUploadResonse(String message, long fileSize, String fileName, String fileType){
		return String.format(FILE_UPLOAD_SUCCESS_RESPONSE, Boolean.TRUE, message,fileSize,fileName,fileType);
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = "uploadDocument")
	public String uploadDocument(	@RequestParam(value="projectId") long projectId,
												@RequestParam(value="receiveDate")String receiveDate,
								 				FileUploadBean fileUploadBean,
								 				HttpServletRequest request,
								 				HttpServletResponse response)throws IOException{
		
		System.out.println("Document Controller >> uploadDocument >> projectId : "+projectId);
		ProjectDetails projectDetails = projectDetailsService.find(projectId);
		
		
		MultipartFile multipartFile = fileUploadBean.getFile();
		System.out.println("filename : "+multipartFile.getOriginalFilename());
		
		
		ProjectDocuments doc = new ProjectDocuments();
		doc.setDocumentType(fileUploadBean.getDocumentTypeId());
		doc.setDocumentName(fileUploadBean.getDocumentName());
		doc.setFileName(multipartFile.getOriginalFilename());
		doc.setFileSize(multipartFile.getSize());
		doc.setContent(multipartFile.getBytes());
		doc.setProject(projectDetails);
		System.out.println("Receive Date : "+receiveDate);
		doc.setReceiveDate(DateUtil.stringToDate(receiveDate));		
		
		doc.setSenderName(LoggedUser.getUser(request).getUserName());
		doc.setCreatedAt(new Date());
		doc.setCreatedBy(LoggedUser.getUser(request));
		
		
		System.out.println("Document Uploaded : "+multipartFile.getOriginalFilename());
		projectDetailsService.createProjectDoc(doc);
		
		
		response.setContentType("text/html");
		HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
		Writer out = responseWrapper.getWriter();
		String json = buildSuccessFileUploadResonse("File uploaded Successfully", 
										fileUploadBean.getFile().getSize(),
										fileUploadBean.getFile().getOriginalFilename(),
										fileUploadBean.getFile().getContentType());
		out.write(json);
		out.close();
		
		System.out.println("Success");
		
		return null;
    }
	
	@RequestMapping(method = RequestMethod.GET, value = "docList")
	public @ResponseBody
	Map<String, Object> documentList(@RequestParam(required=false, value="projectId")Long projectId) {
		System.out.println("Document Controllert >> docList "+projectId);
		if(projectId != null){
			List<ProjectDocumentVo> docs = projectDetailsService.findAllByProject(projectId);
			if(docs != null){
				return JsonModelMap.success().data(docs);
			}else{
				return JsonModelMap.success();
			}
		}else{
			return JsonModelMap.success();
		}
	}
	
	@RequestMapping(method=RequestMethod.GET,value="documentTypes")
  	public @ResponseBody
  	Map<String, Object>documentTypes(){
  		  return JsonModelMap.success().data(qualifierService.getDocumentTypes());
  	} 	
}
